package io.gitee.zhangbinhub.acp.cloud

import io.gitee.zhangbinhub.acp.boot.AcpSchedulerAutoConfiguration
import io.gitee.zhangbinhub.acp.boot.component.AcpTimerTaskSchedulerCtrl
import io.gitee.zhangbinhub.acp.boot.conf.AcpScheduleConfiguration
import io.gitee.zhangbinhub.acp.boot.constant.AcpCoreConstant
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.cloud.context.config.annotation.RefreshScope
import org.springframework.cloud.context.environment.EnvironmentChangeEvent
import org.springframework.context.ApplicationListener

@AutoConfiguration(after = [AcpSchedulerAutoConfiguration::class, AcpCloudLogAutoConfiguration::class])
@RefreshScope
class AcpCloudEnvironmentChangeAutoConfiguration(
    private val logAdapter: LogAdapter,
    private val acpScheduleConfiguration: AcpScheduleConfiguration,
    private val acpTimerTaskSchedulerCtrl: AcpTimerTaskSchedulerCtrl
) : ApplicationListener<EnvironmentChangeEvent> {
    override fun onApplicationEvent(event: EnvironmentChangeEvent) {
        logAdapter.info("configuration items are undergoing changes...")
        logAdapter.info("changed configuration items: ${event.keys}")
        if (acpScheduleConfiguration.autoRestart) {
            event.keys.filter { key -> key.startsWith("spring.task.scheduling") || key.startsWith(AcpCoreConstant.SCHEDULE_PROPERTIES_PREFIX) }
                .apply {
                    if (this.isNotEmpty()) {
                        refreshScheduler()
                    }
                }
        }
    }

    private fun refreshScheduler() {
        logAdapter.info("scheduler configuration items are changed,begin restart scheduler!")
        acpTimerTaskSchedulerCtrl.reStartSchedule(false)
    }
}
